<template>
  <div class="hc-custom-treeselect" :id="treeId">
    <el-input v-if="ctrlProps.showSearch" placeholder="搜索" v-model="searchKey">
      <i slot="prefix" class="el-input__icon el-icon-search"></i>
    </el-input>
    <el-scrollbar class="scroll-Y">
      <el-tree v-if="reloading" ref="treeSelect" :data="options" :disabled="enabled"
               :current-node-key="currentNodeKey"
               :show-checkbox="ctrlProps.showCheckbox"
               :node-key="treeProps.value"
               :highlight-current="ctrlProps.highlightCurrent"
               :expand-on-click-node="ctrlProps.expandOnClickNode"
               :props="treeProps"
               :default-expanded-keys="ctrlProps.expandedKeys"
               :filter-node-method="filterNode" @check-change="onTreeChange"
               @node-click="handleNodeClick">
            <span v-if="data.draggable && ctrlProps.draggable" class="custom-tree-node" slot-scope="{ node,data }"
                  v-draggable="data" data-allow-drop="false" @drag-stop="handleDragStop">
              <span v-if="data[treeProps.icon]" class="custom-tree-icon">
                <svg-icon style="margin-right:4px" :icon-class="data[treeProps.icon]"></svg-icon>
              </span>
              <span v-if="data.tooltip" v-bubble-tooltip="data[treeProps.value]" class="custom-tree-label"
                    v-html="node.label"></span>
              <span v-else class="custom-tree-label" v-html="node.label"></span>
              <span v-if="data.buttonList" class="custom-tree-btnGroup">
                <span v-for="(preBtn,index) in data.buttonList" :key="index" :title="preBtn.btnTitle"
                      class="custom-tree-btn"
                      @click="customClickEvent($event, node, data, preBtn.btnEvent)">
                  <svg-icon style="margin-right:4px" :icon-class="preBtn.iconName"></svg-icon>
                </span>
              </span>
            </span>
            <span v-else class="custom-tree-node" slot-scope="{ node,data }">
                  <span v-if="data[treeProps.icon]" class="custom-tree-icon">
                    <svg-icon style="margin-right:4px" v-if="data[treeProps.icon]" :icon-class="data[treeProps.icon]"></svg-icon>
                  </span>
                  <span v-if="data.tooltip" v-bubble-tooltip="data[treeProps.value]" class="custom-tree-label"
                        v-html="node.label"
                  ></span>
                  <span v-else class="custom-tree-label" v-html="node.label"></span>
                  <span v-if="data.buttonList" class="custom-tree-btnGroup">
                    <span v-for="(preBtn,index) in data.buttonList" :key="index" :title="preBtn.btnTitle"
                          class="custom-tree-btn"
                          @click="customClickEvent($event, node, data, preBtn.btnEvent)">
                      <svg-icon style="margin-right:4px" :icon-class="preBtn.iconName"></svg-icon>
                    </span>
                  </span>
            </span>
      </el-tree>
    </el-scrollbar>
  </div>
</template>

<script>
import PinYinMatch from 'pinyin-match'
import draggable from './components/HCDraggable'
import bubbleTooltip from './components/HCBubbleTooltip'
import { EventBus } from '../HCEventBus/eventBus'
import { clickEvent } from '../../event/eventClick'

export default {
  directives: {
    draggable,
    bubbleTooltip
  },
  props: {
    // 树组件ID标识
    treeId: {
      type: String,
      required: true
    },
    // 禁用
    enabled: {
      type: Boolean,
      required: false,
      default: false
    },
    // 自定义树组件配置
    ctrlProps: {
      type: Object,
      required: false,
      default: {
        // 当前节点
        currentNodeKey: null,
        // 是否允许拖拽
        draggable: false,
        // 拖拽绑定的字段
        dragField: 'label',
        // 拖拽绑定显示的字段
        dragShowField: 'label',
        // 是否显示搜索框
        showSearch: true,
        // 是否显示复选框
        showCheckbox: true,
        // 是否高亮当前节点
        highlightCurrent: true,
        // 是否点击展开节点
        expandOnClickNode: true,
        // 默认展开那些节点
        expandedKeys: [],
        // 设置那些节点点击时触发事件
        selectedKeys: []
      }
    },
    // 树组件备选值
    options: {
      type: Array,
      required: false,
      default: []
    },
    // 双向绑定值
    value: {
      type: [String, Array],
      required: false,
      default: []
    },
    // 父级表单对象
    otherObj: {
      type: [Object, Function],
      default: () => {
        return {}
      }
    }
  },
  name: 'index',
  data() {
    return {
      // 当前节点
      currentNodeKey: this.ctrlProps.currentNodeKey || this.value || null,
      // tree控件的搜索
      searchKey: '',
      // 树组件配置
      treeProps: {
        children: 'children',
        label: 'label',
        value: 'unid',
        icon: 'icon'
      },
      // 是否重新加载
      reloading: true
    }
  },
  watch: {
    // 监听树控件搜索
    searchKey(val) {
      this.$refs.treeSelect.filter(val)
    },
    // 监听报表组件配置
    options: {
      handler: function(val) {
        console.log(val,"====================")
        this.reloading = false
        this.$nextTick(() => {
          this.reloading = true
        })
      },
      deep: true
    },
    ctrlProps:{
      handler: function (newVal, oldVal)
      {
        this.currentNodeKey = newVal.currentNodeKey;
      },
      deep: true
    },
    // 监听双向绑定值的变化
    value: {
      handler: function (newVal, oldVal)
      {
        this.$emit('input', newVal)
      },
      deep: true
    }
  },
  mounted() {
    if (this.ctrlProps.replaceFields) {
      this.treeProps = {
        ...this.treeProps,
        children: this.ctrlProps.replaceFields.children || this.treeProps.children,
        label: this.ctrlProps.replaceFields.title || this.treeProps.label,
        value: this.ctrlProps.replaceFields.key || this.treeProps.value,
        icon: this.ctrlProps.replaceFields.icon || this.treeProps.icon
      }
    }
    console.log('自定义树组件加载......', this.ctrlProps, this.value, this.treeProps)
  },
  methods: {
    // 树过滤
    filterNode(value, data) {
      if (!value) return true
      if (data) {
        return PinYinMatch.match(data[this.treeProps.label], value)
      } else {
        return false
      }
    },
    // 树选中
    onTreeChange() {
      this.value = this.$refs.treeSelect.getCheckedKeys()
    },
    // 拖拽结束
    handleDragStop({ draggedData, droppedData }) {
      console.log(EventBus, 'EventBus')
      // 将拖拽数据通过 EventBus 发送
      EventBus.$emit('drag-data', {
        label : draggedData[this.ctrlProps.dragShowField],
        value : draggedData[this.ctrlProps.dragField],
      })
    },
    // 自定义树点击事件
    customClickEvent(event, node, data, btnEvent) {
      event.stopPropagation()
      console.log(node, data, btnEvent, this.ctrlProps.selectedKeys, '=============cs')
      if (btnEvent) {
        let otherObj = typeof this.otherObj == 'function' ? this.otherObj() : this.otherObj
        clickEvent({
          btnEvent: btnEvent,
          ...btnEvent
        }, otherObj.getFormParam(), otherObj)
      }
    },
    // 树节点点击事件
    handleNodeClick(data, node)
    {
      console.log(data, node, '====================')
      if (data && data.event)
      {
        let otherObj = typeof this.otherObj == 'function' ? this.otherObj() : this.otherObj
        clickEvent({
          btnEvent: data.event,
          ...data.event
        }, otherObj.getFormParam(), otherObj)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.hc-custom-treeselect {
  .hc-dragging {
    opacity: 0.5;
  }
}

.scroll-Y {
  width: 100%;
  height: 200px;

  ::v-deep .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}
</style>
